package com.sj.hh.request;


import android.content.Context;
import android.text.TextUtils;

import com.sj.hh.request.base.BaseRequestClient;

import java.util.ArrayList;
import java.util.List;

import cn.rongcloud.im.server.network.async.OnDataListener;
import cn.rongcloud.im.server.network.http.HttpException;
import cn.rongcloud.im.server.response.friendcircle.CommentInfo;
import cn.rongcloud.im.server.response.friendcircle.LikesInfo;
import cn.rongcloud.im.server.response.friendcircle.MomentContent;
import cn.rongcloud.im.server.response.friendcircle.MomentsInfo;
import cn.rongcloud.im.server.response.user.UserInfo;


/**
 * Created by huluhong on 2018/7/27.
 * <p>
 * 朋友圈（社区）时间线请求
 */

public class MomentsRequest extends BaseRequestClient<List<MomentsInfo.DataBean>> {

    private static final int REQUEST_REFRESH = 0x10;
    private static final int REQUEST_LOADMORE = 0x11;
    private int curPage = 1;

    private static boolean isFirstRequest = true;

    public MomentsRequest() {
    }

    public MomentsRequest setCurPage(int page) {
        this.curPage = page;
        return this;
    }


    @Override
    protected void executeInternal(Context context, final int requestType, boolean showDialog) {
        if (mAsyncTaskManager != null) {
            mAsyncTaskManager.request(context, requestType, new OnDataListener() {
                @Override
                public Object doInBackground(int requestCode, String parameter) throws HttpException {
                    if (requestType == 0x10){/**朋友圈*/
                        return mAction.getListFriendByPage(curPage, 20);
                    } else if (requestType == 0x20){/**社区*/
                        return mAction.listCommunityByPage(curPage, 20);
                    }else {
                        return null;
                    }
                }

                @Override
                public void onSuccess(int requestCode, Object result) {
                    if (result != null) {
                        MomentsInfo momentsInfo = (MomentsInfo) result;
                        queryCommentAndLikes(momentsInfo);
                    }
                }

                @Override
                public void onFailure(int requestCode, int state, Object result) {

                }
            });
        }
//        BmobQuery<MomentsInfo> query = new BmobQuery<>();
//        query.order("-createdAt");
//        query.include(MomentsFields.AUTHOR_USER + "," + MomentsFields.HOST);
//        query.setLimit(count);
//        query.setSkip(curPage * count);
//        query.setCachePolicy(isFirstRequest? BmobQuery.CachePolicy.CACHE_ELSE_NETWORK: BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
//        query.findObjects(new FindListener<MomentsInfo>() {
//            @Override
//            public void done(List<MomentsInfo> list, BmobException e) {
//                if (!ToolUtil.isListEmpty(list)) {
//                    queryCommentAndLikes(list);
//                }
//            }
//        });

    }

    private void queryCommentAndLikes(final MomentsInfo momentsList) {
        try {
            List<MomentsInfo.DataBean> data = momentsList.getData();
            if (data != null) {
                for (MomentsInfo.DataBean dataBean : data) {
                    MomentContent momentContent = new MomentContent();
                    momentContent.addText(dataBean.getTrendsContent());

                    /**图片数据*/
                    if (dataBean.getTrendsImg() != null) {
                        ArrayList<String> pics = new ArrayList<>();
                        List<MomentsInfo.DataBean.TrendsImgBean> trendsImg = dataBean.getTrendsImg();
                        for (MomentsInfo.DataBean.TrendsImgBean trendsImgBean : trendsImg) {
                            pics.add(trendsImgBean.getImgpath());
                        }
                        momentContent.setPics(pics);
                    }
                    dataBean.setContent(momentContent);


                    /**评论数据*/
                    List<CommentInfo> commentInfoList = new ArrayList<>();
                    List<MomentsInfo.DataBean.TrendsCommentBean> trendsComment = dataBean.getTrendsComment();
                    if (trendsComment != null) {
                        for (MomentsInfo.DataBean.TrendsCommentBean trendsCommentBean : trendsComment) {
                            //评论创建者
                            UserInfo author = new UserInfo();
                            author.setUserid(trendsCommentBean.getUserid()+"");
                            author.setUsername(trendsCommentBean.getUserName());
                            String nick;
                            if (!TextUtils.isEmpty(trendsCommentBean.getUserRemark()))
                                nick = trendsCommentBean.getUserRemark();
                            else
                                nick = trendsCommentBean.getUserName();
                            author.setNick(nick);

                            CommentInfo commentInfo = new CommentInfo();
                            commentInfo.setContent(trendsCommentBean.getContent());
                            commentInfo.setTrendsid(dataBean.getTrendsId() + "");
                            commentInfo.setCommentid(trendsCommentBean.getId());
                            commentInfo.setAuthor(author);

                            //评论回复人
                            if (trendsCommentBean.getUserid() != dataBean.getUserId()){
                                UserInfo reply = new UserInfo();
                                reply.setUserid(dataBean.getUserId()+"");
                                reply.setUsername(dataBean.getUserName());
                                String replyNick;
                                if (!TextUtils.isEmpty(dataBean.getUserRemark()))
                                    replyNick = dataBean.getUserRemark();
                                else
                                    replyNick = dataBean.getUserName();
                                reply.setNick(replyNick);
                                commentInfo.setReply(reply);
                            }

                            commentInfoList.add(commentInfo);
                        }
                    }
                    dataBean.setCommentList(commentInfoList);

                    /**点赞数据*/
                    if (dataBean.getTrendsCommentLike() != null){
                        ArrayList<LikesInfo> likesInfos = new ArrayList<>();
                        for (MomentsInfo.DataBean.TrendsCommentLikeBean likeBean : dataBean.getTrendsCommentLike()) {
                            UserInfo userInfo = new UserInfo();
                            userInfo.setUsername(likeBean.getUserName());
                            userInfo.setUserid(likeBean.getUserid()+"");

                            LikesInfo likesInfo = new LikesInfo(userInfo,dataBean);
                            likesInfos.add(likesInfo);
                        }
                        dataBean.setLikesList(likesInfos);
                    }
                }

                onResponseSuccess(data, getRequestType());
            }
            if (REQUEST_REFRESH == getRequestType()) {
                curPage = 1;
            } else if (REQUEST_LOADMORE == getRequestType()) {
                curPage++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private void queryCommentAndLikes(final List<MomentsInfo> momentsList) {
//        /**
//         * 因为bmob不支持在查询时把关系表也一起填充查询，因此需要手动再查一次，同时分页也要手动实现。。
//         * oRz，果然没有自己写服务器来的简单，好吧，都是在下没钱的原因，我的锅
//         */
//        final List<CommentInfo> commentInfoList = new ArrayList<>();
//        final List<LikesInfo> likesInfoList = new ArrayList<>();
//
//        final boolean[] isCommentRequestFin = {false};
//        final boolean[] isLikesRequestFin = {false};
//
//        BmobQuery<CommentInfo> commentQuery = new BmobQuery<>();
//        commentQuery.include(MOMENT + "," + REPLY_USER + "," + AUTHOR_USER);
//        List<String> id = new ArrayList<>();
//        for (MomentsInfo momentsInfo : momentsList) {
//            id.add(momentsInfo.getObjectId());
//        }
//        commentQuery.addWhereContainedIn(MOMENT, id);
//        commentQuery.order("createdAt");
//        commentQuery.setLimit(1000);//默认只有100条数据，最多1000条
//        commentQuery.setCachePolicy(isFirstRequest? BmobQuery.CachePolicy.CACHE_ELSE_NETWORK: BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
//        commentQuery.findObjects(new FindListener<CommentInfo>() {
//            @Override
//            public void done(List<CommentInfo> list, BmobException e) {
//                isCommentRequestFin[0] = true;
//                if (!ToolUtil.isListEmpty(list)) {
//                    commentInfoList.addAll(list);
//                }
//                mergeData(isCommentRequestFin[0], isLikesRequestFin[0], commentInfoList, likesInfoList, momentsList, e);
//            }
//        });
//
//        BmobQuery<LikesInfo> likesInfoBmobQuery = new BmobQuery<>();
//        likesInfoBmobQuery.include(LikesInfo.LikesField.MOMENTID + "," + LikesInfo.LikesField.USERID);
//        likesInfoBmobQuery.addWhereContainedIn(LikesInfo.LikesField.MOMENTID, id);
//        likesInfoBmobQuery.order("createdAt");
//        likesInfoBmobQuery.setLimit(1000);
//        likesInfoBmobQuery.setCachePolicy(isFirstRequest? BmobQuery.CachePolicy.CACHE_ELSE_NETWORK: BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);
//        likesInfoBmobQuery.findObjects(new FindListener<LikesInfo>() {
//            @Override
//            public void done(List<LikesInfo> list, BmobException e) {
//                isLikesRequestFin[0] = true;
//                if (!ToolUtil.isListEmpty(list)) {
//                    likesInfoList.addAll(list);
//                }
//                mergeData(isCommentRequestFin[0], isLikesRequestFin[0], commentInfoList, likesInfoList, momentsList, e);
//            }
//        });
//
//    }
//
//
//    private void mergeData(boolean isCommentRequestFin,
//                           boolean isLikeRequestFin,
//                           List<CommentInfo> commentInfoList,
//                           List<LikesInfo> likesInfoList,
//                           List<MomentsInfo> momentsList,
//                           BmobException e) {
//        if (!isCommentRequestFin || !isLikeRequestFin) return;
//        if (e != null) {
//            onResponseError(e, getRequestType());
//            return;
//        }
//        if (ToolUtil.isListEmpty(momentsList)) {
//            onResponseError(new BmobException("动态数据为空"), getRequestType());
//            return;
//        }
//        curPage++;
//
//        HashMap<String, MomentsInfo> map = new HashMap<>();
//        for (MomentsInfo momentsInfo : momentsList) {
//            map.put(momentsInfo.getMomentid(), momentsInfo);
//        }
//
//        for (CommentInfo commentInfo : commentInfoList) {
//            MomentsInfo info = map.get(commentInfo.getMoment().getMomentid());
//            if (info != null) {
//                info.addComment(commentInfo);
//            }
//        }
//
//        for (LikesInfo likesInfo : likesInfoList) {
//            MomentsInfo info = map.get(likesInfo.getMomentsid());
//            if (info != null) {
//                info.addLikes(likesInfo);
//            }
//        }
//
//        onResponseSuccess(momentsList, getRequestType());
//
//    }

    @Override
    protected void onResponseSuccess(List<MomentsInfo.DataBean> response, int requestType) {
        super.onResponseSuccess(response, requestType);
        isFirstRequest = false;
    }
}
